package com.soa.zuul.util;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.netflix.zuul.context.RequestContext;
import com.soa.zuul.entity.GatewayHttpApi;
import com.soa.zuul.entity.GatewayService;
import com.soa.zuul.entity.GatewayServiceLogVO;
import com.soa.zuul.entity.GatewayUser;
import com.soa.zuul.service.GatewayHttpApiService;

public class RequestUtil {
	public final static Logger logger = LoggerFactory.getLogger(RequestUtil.class);
	/**
     * 获取Ip地址
     * @param request
     * @return
     */
	public static String getIpAdrress(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }
	
	
	/**
     * 获取token地址
     * @param request
     * @return
     */
	public static String getAccessToken(HttpServletRequest request) {
		String auth = request.getHeader("Authorization");
		String accessToken = null;
		if(auth!=null){
			String[] authArray= auth.split(" ");
			if(authArray.length>1){
				accessToken = auth.split(" ")[1];
			}
		}
        if(org.springframework.util.StringUtils.isEmpty(accessToken)){
        	accessToken = request.getParameter("access_token");
        }
        return accessToken;
	}
	
	
	public static GatewayServiceLogVO SendZuulResponseError(CodeMsg codeMsg,RequestContext ctx){
		String body =Json.GSON.toJson(codeMsg);
		ctx.getResponse().setContentType("text/html;charset=UTF-8");
		if(codeMsg.getResultcode()!=CodeMsg.SUCCESS.getResultcode()){
			ctx.setSendZuulResponse(false); // 过滤该请求，不对其进行路由
			ctx.setResponseBody(body);  //设置验证失败返回内容
		}
		String method = (String)ctx.get("method");
		String access_token = (String)ctx.get("access_token");
		String ip =  (String)ctx.get("ip");
		long permissionStatTime  = (Long)ctx.get("permissionStatTime");
		String params = (String)ctx.get("params"); 
		String requestURI =(String)ctx.get("uri");
		String userAgent =(String)ctx.get("userAgent");
		GatewayServiceLogVO gatewayServiceLog = new GatewayServiceLogVO();
		gatewayServiceLog.setApikey(access_token);
		gatewayServiceLog.setUrl(requestURI);
		gatewayServiceLog.setUserAgent(userAgent);
		gatewayServiceLog.setIp(ip);
		gatewayServiceLog.setExecuteParams(params);
		gatewayServiceLog.setExecuteResult(body);
		 Calendar now = Calendar.getInstance();
		 now.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));//important
		gatewayServiceLog.setOperateTime(new Timestamp(now.getTime().getTime()));
		//计算转发耗时
		long permissionEndTime = System.currentTimeMillis();
		gatewayServiceLog.setExecuteResult(body);
		gatewayServiceLog.setExecuteTime(new BigDecimal(permissionEndTime-permissionStatTime));
		gatewayServiceLog.setExecuteResultState(codeMsg.getResultcode()+"");
		logger.info("请求参URL失败: "+requestURI+";方法为："+method+";  请求参用户token: "+access_token+";  请求参数："+params+";  应答结果："+body+";  转发耗时："+(gatewayServiceLog.getExecuteTime())+"毫秒");
		return gatewayServiceLog;
	}
	
	
	public static GatewayServiceLogVO SendZuulResponseSucess(String body,RequestContext ctx){
		ctx.getResponse().setContentType("text/html;charset=UTF-8");
		String method = (String)ctx.get("method");
		String access_token = (String)ctx.get("access_token");
		String ip =  (String)ctx.get("ip");
		if(ctx.get("permissionStatTime")==null){
			ctx.set("permissionStatTime",System.currentTimeMillis());
		}
		long permissionStatTime  = (Long)ctx.get("permissionStatTime");
		Map<String, String[]> map = ctx.getRequest().getParameterMap();
		String params = Json.GSON.toJson(map); 
		String requestURI =(String)ctx.get("uri");
		String userAgent =(String)ctx.get("userAgent");
		GatewayHttpApi gatewayHttpApi=(GatewayHttpApi)ctx.get("gatewayHttpApi");
		GatewayService gatewayService=(GatewayService)ctx.get("gatewayService");
		GatewayUser gatewayUser=(GatewayUser)ctx.get("gatewayUser");
		GatewayServiceLogVO gatewayServiceLog = new GatewayServiceLogVO();
		gatewayServiceLog.setApikey(access_token);
		gatewayServiceLog.setUrl(requestURI);
		gatewayServiceLog.setUserAgent(userAgent);
		gatewayServiceLog.setIp(ip);
		gatewayServiceLog.setExecuteParams(params);
		gatewayServiceLog.setExecuteResult(body);
		if(gatewayHttpApi!=null){
			gatewayServiceLog.setApiId(gatewayHttpApi.getId());
			gatewayServiceLog.setApiName(gatewayHttpApi.getApiName());
		}
		 Calendar now = Calendar.getInstance();
		 now.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));//important
		gatewayServiceLog.setOperateTime(new Timestamp(now.getTime().getTime()));
		if(gatewayService!=null){
			gatewayServiceLog.setGatewayServiceId(gatewayService.getId());
			gatewayServiceLog.setGatewayServiceName(gatewayService.getServiceName());
			gatewayServiceLog.setGatewayServiceType(gatewayService.getExecuteType());
			gatewayServiceLog.setExecuteThemeId(gatewayService.getThemeId());
		}
		
		if(gatewayUser!=null){
			gatewayServiceLog.setGatewayUserId(gatewayUser.getId());
			gatewayServiceLog.setGatewayUserRealname(gatewayUser.getRealname());
		}
		
		//计算转发耗时
		long permissionEndTime = System.currentTimeMillis();
		gatewayServiceLog.setExecuteResult(body);
		gatewayServiceLog.setExecuteTime(new BigDecimal(permissionEndTime-permissionStatTime));
		gatewayServiceLog.setExecuteResultState(CodeMsg.SUCCESS.getResultcode()+"");
		logger.debug("请求参URL成功: "+requestURI+";方法为："+method+";  请求参用户token: "+access_token+";  请求参数："+params+";  应答结果："+"?"+";  转发耗时："+(gatewayServiceLog.getExecuteTime())+"毫秒");
		return gatewayServiceLog;
	}
}
